package com.xm.xmapp.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.model.NaviLatLng;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xm.xmapp.BasicNaviActivity;
import com.xm.xmapp.MainActivity;
import com.xm.xmapp.R;
import com.xm.xmapp.ShowURLActivity;
import com.xm.xmapp.app.Constants;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.Type;
import com.xm.xmapp.base.BaseFragment;
import com.xm.xmapp.customview.MyDialog1;
import com.xm.xmapp.customview.PasswordDialog;
import com.xm.xmapp.customview.TipDialog;
import com.xm.xmapp.dialog.ShortTimeTipDialog;
import com.xm.xmapp.dialog.SongCheDialog;
import com.xm.xmapp.dialog.TipLeftRightDialog;
import com.xm.xmapp.http.ChangDataTools;
import com.xm.xmapp.http.MyVolleyError;
import com.xm.xmapp.map.ClusterItem;
import com.xm.xmapp.myinterface.BaseDataInterFace;
import com.xm.xmapp.myinterface.DialogInterFace;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.myinterface.MainActivityInterFace;
import com.xm.xmapp.myinterface.MyDialogButton;
import com.xm.xmapp.myinterface.ScrollInterFaceAble;
import com.xm.xmapp.request.bean.App_add_user_orderRequest;
import com.xm.xmapp.request.bean.Get_network_infoRequest;
import com.xm.xmapp.request.bean.Subscribe_car_orderRequest;
import com.xm.xmapp.response.bean.CarInfoBean;
import com.xm.xmapp.response.bean.CustomHeightBean;
import com.xm.xmapp.response.bean.ResponseAllNetworkCoords.Point;
import com.xm.xmapp.response.bean.ResponsePlieNetworkInfo;
import com.xm.xmapp.response.bean.ResponseSubscribeCarOrder;
import com.xm.xmapp.response.bean.ResponseUserBean;
import com.xm.xmapp.tools.Des4;

import com.xm.xmapp.tools.StringTools;
import com.xm.xmapp.tools.Tools;


public class ShortTimeCarInfoFragment extends BaseFragment implements OnClickListener,ScrollInterFaceAble {

	private CarInfoBean bean;

	private String juli;
	private Point item;
	private Dialog mydialog;


	private TextView tv_car_number, tv_genre_name, tv_car_seat, tv_cost, tv_endurance, tv_status ,tvCarAddress;
	private View v_line;
	private LinearLayout ll_btn, layout, bottom;
	private RelativeLayout rel_usecar,rel_subscribe;


	private ResponseUserBean userbean;
	private DisssmissInterFace disssmissInterFace;
	/**
	 * 是否需要弹出打电话提示框
	 */
	boolean isPhone = false;

	/**
	 * 单个网点信息
	 */
	ResponsePlieNetworkInfo base;
	boolean isRent;

	public ShortTimeCarInfoFragment() {
		isSuppertLazyLoad = false;
	}



	public static ShortTimeCarInfoFragment newInstance(ClusterItem bean, ClusterItem item, boolean isRent) {
		String juli;
		LatLng latLng = MyAppcation.getMyAppcation().getMyLocation();
		if (latLng != null)
			juli = StringTools.getJuliString(AMapUtils.calculateLineDistance(latLng, bean.getLatLng()) / 1000) + "";
		else
			juli = "0";

		ShortTimeCarInfoFragment newFragment = new ShortTimeCarInfoFragment();
		Bundle bundle = new Bundle();
		bundle.putString("juli", juli);
		bundle.putSerializable("bean", (CarInfoBean) bean);
		bundle.putSerializable("item", (Point) item);
		bundle.putBoolean("isRent", isRent);
		newFragment.setArguments(bundle);
		return newFragment;
	}

	@Override
	public int setContentView() {
		return R.layout.fragment_shorttime_carinfo;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public void initView() {

		tv_car_number = (TextView) findViewById(R.id.tv_car_number);
		tv_endurance = (TextView) findViewById(R.id.tv_endurance);
		bottom = (LinearLayout) findViewById(R.id.bottom);
		tv_status = (TextView) findViewById(R.id.tv_status);
		tv_cost = (TextView) findViewById(R.id.tv_cost);
		layout = (LinearLayout) findViewById(R.id.layout);
		tv_genre_name = (TextView) findViewById(R.id.tv_genre_name);
		tv_car_seat = (TextView) findViewById(R.id.tv_car_seat);
		rel_usecar = (RelativeLayout) findViewById(R.id.rel_usecar);
		rel_subscribe = (RelativeLayout) findViewById(R.id.rel_subscribe);
		v_line = (View) findViewById(R.id.v_line);
		ll_btn = (LinearLayout) findViewById(R.id.ll_btn);
		tvCarAddress = (TextView) findViewById(R.id.tv_car_address);
		isVisible = true;

	}
	public void setOffext(int currentProgress){
		if(ll_btn!=null && mRect!=null) {
			ll_btn.layout(mRect.left, -currentProgress + mRect.top, mRect.right, mRect.bottom - currentProgress);
		}
	}

	@Override
	public void initRect() {
		if(mRect==null) {
			int left = ll_btn.getLeft();
			int top = ll_btn.getTop();
			int right = ll_btn.getRight();
			int bottom = ll_btn.getBottom();
			mRect = new Rect(left, top, right, bottom);
		}
	}

	private  Rect mRect;
	@Override
	public void ViewTreeObserver() {

		super.ViewTreeObserver();
		CustomHeightBean bean = new CustomHeightBean();
		bean.ExitOffset = layout.getHeight();
		bean.MaxOffset = bottom.getHeight() - ll_btn.getHeight();
		initRect();
		bean.flag = MainActivityInterFace.INTT_STATUS_NO_ONCLICK;
		MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.CHANGE_UI_CODE, bean);

	}

	@Override
	public void initData() {

		tv_car_number.setText(bean.car_number);
		tvCarAddress.setText(item.getName());
//		text1.setText(juli + "km");
		tv_endurance.setText(bean.getEndurance() + "km");
//		text3.setText(bean.getDianLiang() + "%");
//		if (bean.getDianLiang() < 30) {
//			dianliangImg.setImageResource(R.mipmap.dianliang3);
//		} else if (bean.getDianLiang() > 70) {
//			if (bean.getDianLiang() != 100)
//				dianliangImg.setImageResource(R.mipmap.dianliang_icon);
//			else
//				dianliangImg.setImageResource(R.mipmap.mandian);
//		} else {
//			dianliangImg.setImageResource(R.mipmap.dianliang2);
//		}
		tv_genre_name.setText(bean.car_genre_name);
		tv_car_seat.setText(bean.car_seat + "座");
		tv_cost.setText(bean.off_minute_money + "元/分钟 ~" + bean.on_minute_money + "元/分钟");
//		ImageLoader.getInstance().displayImage(bean.car_genre_img, img, Options.getListOptions(R.mipmap.moren));
		disssmissInterFace = new DisssmissInterFace() {

			@Override
			public void putError(VolleyError error) {

				promptDialog.dismiss();
				MyVolleyError e = (MyVolleyError) error;
				switch (e.data) {
				case "3001":
					bean.is_subscribe = 1;
					setStatus();
					break;
				case "10002":
					MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class,
							Type.A_Main.CAR_HAVE_RENT_CODE);
					break;
				default:
					break;
				}
			}
		};

//		if (item != null) {
//			if (item.is_send_car_service == 1) {
//				songche.setVisibility(View.VISIBLE);
//			} else {
//				songche.setVisibility(View.GONE);
//			}
//		} else {
//			songche.setVisibility(View.GONE);
//		}
		setStatus();
//		songche.setVisibility(View.VISIBLE);
	}

	private void setStatus() {

		if (bean.is_rent == 0 || isRent) {
			tv_status.setVisibility(View.VISIBLE);
			rel_subscribe.setVisibility(View.GONE);
			rel_usecar.setVisibility(View.GONE);
			tv_status.setText(bean.disabled_reason);
			v_line.setVisibility(View.GONE);
		} else {
			tv_status.setVisibility(View.GONE);
			rel_subscribe.setVisibility(View.VISIBLE);
			rel_usecar.setVisibility(View.VISIBLE);
			v_line.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void initEvent() {

		rel_subscribe.setOnClickListener(this);
//		go.setOnClickListener(this);
		rel_usecar.setOnClickListener(this);
		tv_cost.setOnClickListener(this);
//		songche.setOnClickListener(this);

	}

	/**
	 * 获取单个网点信息
	 * 
	 * @param item
	 */
	private void get_network_infoRequest(final ClusterItem item) {
		Get_network_infoRequest requestBean = new Get_network_infoRequest();
		requestBean.networkId = item.getNetworkId();
		promptDialog.show();
		MyAppcation.getMyAppcation().getPostData(this, requestBean, new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {
				promptDialog.dismiss();
				base = JSON.parseObject(response, ResponsePlieNetworkInfo.class);
				if (StringTools.isTime(base.send_car_service_time)) {
					SongCheDialog songChedialog = new SongCheDialog(getActivity(), base);
					songChedialog.setOnSongCheDialog(new SongCheDialog.OnSongCheDialog() {

						@Override
						public void yongche() {
							rel_subscribe.performClick();
							isPhone = true;
						}

						@Override
						public void phone() {

						}
					});

					songChedialog.show();
				} else {
					TipDialog tipDialog = new TipDialog(getActivity(), "温馨提示", "", new MyDialogButton() {

						@Override
						public void setTitle(int flag, String str) {

						}
					});
					tipDialog.show();
					String str_text = "抱歉，此时段无法为您提供送车服务！\n我们的服务时间为：" + base.send_car_service_time;
					tipDialog.setContent(StringTools.getStyle(27, base.send_car_service_time, str_text));
					tipDialog.setRightText("我知道了");
				}
			}
		}, new DisssmissInterFace() {

			@Override
			public void putError(VolleyError error) {
				promptDialog.dismiss();
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.go:
			if (MyAppcation.getMyAppcation().getMyLocation() != null) {
				intent = new Intent(MyAppcation.getMyAppcation(), BasicNaviActivity.class);
				NaviLatLng mEndLatlng = new NaviLatLng(bean.car_latitude, bean.car_longitude);
				NaviLatLng mStartLatlng = new NaviLatLng(MyAppcation.getMyAppcation().getMyLocation().latitude,MyAppcation.getMyAppcation().getMyLocation().longitude);
				intent.putExtra("mStartLatlng", mStartLatlng);
				intent.putExtra("mEndLatlng", mEndLatlng);
				startActivity(intent);
			} else {
				Tools.showMessage("导航失败，未获取到您的位置信息!");
			}
			break;

//		case R.id.songche:
//			MyDialog1 myDialog1;
//			if (bean.is_maintain == 1) {
//				myDialog1 = new MyDialog1(getActivity(), "温馨提示", "当前车辆维护中", "我知道了");
//				myDialog1.show();
//			} else if (bean.is_subscribe == 1) {
//				myDialog1 = new MyDialog1(getActivity(), "温馨提示", "当前车辆被预约", "我知道了");
//				myDialog1.show();
//			} else if (bean.is_fault == 1) {
//				myDialog1 = new MyDialog1(getActivity(), "温馨提示", "当前车辆不可用", "我知道了");
//				myDialog1.show();
//			} else {
//				get_network_infoRequest(item);
//			}
//
//			break;

		case R.id.tv_cost:

			ShortTimeTipDialog fenShiTipDialog = new ShortTimeTipDialog(getActivity(), "" + bean.on_minute_money
					+ "元/分钟", "" + bean.off_minute_money + "元/分钟", bean.starting_fare, bean.day_max_money);
			fenShiTipDialog.show();
			break;

		case R.id.rel_subscribe:
			userbean = MyAppcation.getMyAppcation().getUserBean();
			promptDialog.show();
			ChangDataTools.Get_user_information_statusRequest(userbean, getActivity(), new BaseDataInterFace() {

				@Override
				public void success() {
					promptDialog.dismiss();
					TipDialog tipDialog = new TipDialog(getActivity(), "温馨提示", "是否立即预约?", new MyDialogButton() {

						@Override
						public void setTitle(int flag, String str) {
							yuyue();
						}
					});
					tipDialog.show();
				}

				@Override
				public void fail() {
					promptDialog.dismiss();
				}
			});

			break;
		case R.id.rel_usecar:
			userbean = MyAppcation.getMyAppcation().getUserBean();
			promptDialog.show();
			ChangDataTools.Get_user_information_statusRequest(userbean, getActivity(), new BaseDataInterFace() {

				@Override
				public void success() {
					promptDialog.dismiss();
					showBuilder("开始用车", "请输入6位数用车密码", 2);
				}

				@Override
				public void fail() {
					promptDialog.dismiss();
				}
			});

			break;
		default:
			break;
		}
	}

	/**
	 * 预约车辆
	 */
	private void yuyue() {

		Subscribe_car_orderRequest requestBean = new Subscribe_car_orderRequest();
		requestBean.car_id = bean.car_id;
		/**
		 * 是否是扫码租车
		 */
		if (item != null)
			requestBean.network_id = item.networkId;
		else
			requestBean.network_id = bean.network_id;

		GetDataInterFace<String> listener = new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {

				promptDialog.dismiss();
				ResponseSubscribeCarOrder base = JSON.parseObject(response, ResponseSubscribeCarOrder.class);
				if (base.is_free != 0) {
					CustomHeightBean bean = new CustomHeightBean();
					bean.flag = MainActivityInterFace.ORDER_STATUS_CAHANGE;
					MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.CHANGE_UI_CODE,
							bean);
				} else {
					showBuilder("温馨提示", "今天免费预约次数用完,点击确定直接走用车流程", 0);
				}
			}
		};

		promptDialog.show();
		MyAppcation.getMyAppcation().getPostData(this.getActivity(), requestBean, listener, disssmissInterFace);
	}

	/**
	 *
	 *            ，0是免费预约次数用完1是取消预约2立即用车
	 */
	protected void showBuilder(String title, String message, int flag) {

		if (flag != 2) {
			mydialog = new TipLeftRightDialog(getActivity(), title, message, flag);
			((TipLeftRightDialog) mydialog).setDialogInterFace("取消", "确定", new DialogInterFace() {
				@Override
				public void right(int flag, Object t) {

					switch (flag) {
					case 0:
						mydialog.dismiss();
						showBuilder("开始用车", "请输入6位数用车密码", 2);
						break;

					case 2:
						mydialog.dismiss();
						userCar(t.toString());
						break;
					default:
						break;
					}
				}

				@Override
				public void left(int flag, Object t) {

					mydialog.dismiss();
				}
			}).show();

		} else {
			mydialog = new PasswordDialog(getActivity(), title, message, flag);
			((PasswordDialog) mydialog).setDialogInterFace("取消", new DialogInterFace() {

				@Override
				public void right(int flag, Object t) {

					switch (flag) {

					case 0:
						mydialog.dismiss();
						showBuilder("开始用车", "请输入6位数用车密码", 2);
						break;

					case 2:

						mydialog.dismiss();
						userCar(t.toString());
						break;

					default:
						break;
					}
				}

				@Override
				public void left(int flag, Object t) {

					mydialog.dismiss();
				}
			}).show();

		}

	}

	/**
	 * @param string
	 * 
	 */
	protected void userCar(String string) {

		App_add_user_orderRequest requestBean = new App_add_user_orderRequest();
		requestBean.user_pin = Des4.encode(string);
		requestBean.car_id = bean.car_id;
		requestBean.subscribe_order_id = 0;
		if (item != null)
			requestBean.network_id = item.networkId;
		else
			requestBean.network_id = bean.network_id;

		if (isPhone) {
			requestBean.use_car_type = 1;
		} else {
			requestBean.use_car_type = 0;
		}

		GetDataInterFace<String> listener = new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {

				promptDialog.dismiss();
				mydialog.dismiss();
				CustomHeightBean bean = new CustomHeightBean();
				bean.flag = MainActivityInterFace.ORDER_STATUS_CAHANGE;
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.CHANGE_UI_CODE, bean);
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.SHORT_RENT_GET_CAR);

			}
		};

		promptDialog.show();
		MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean, listener, disssmissInterFace);

	}

	@Override
	public void getData(Bundle savedInstanceState) {
		Bundle bundle = getArguments();
		if (bundle != null) {
			juli = bundle.getString("juli");
			bean = (CarInfoBean) bundle.getSerializable("bean");
			item = (Point) bundle.getSerializable("item");
			isRent = bundle.getBoolean("isRent", false);
		}
	}

}
